/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.castor.castor;

import cn.easyplatform.castor.Castor;
import cn.easyplatform.castor.FailToCastObjectException;
import cn.easyplatform.lang.Lang;
import cn.easyplatform.lang.Strings;

/**
 * 根据一个字符串将其转换成 Number 类型。这里有几个规则
 * <ul>
 * <li>如果 Number 为原生类型，空白串将被转换成 0
 * <li>如果 Number 为外覆类，空白串将被转换成 null
 * </ul>
 * 
 * 如果转换失败，将抛出 FailToCastObjectException
 * 
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a>
 */
public abstract class String2Number<T> extends Castor<String, T> {

	protected boolean _isNull(String str) {
		return Strings.isBlank(str) || "null".equalsIgnoreCase(str);
	}

	protected abstract T getPrimitiveDefaultValue();

	protected abstract T valueOf(String str);

	@Override
	public T cast(String src, Class<?> toType, String... args) {
		if (Strings.isBlank(src) || "null".equalsIgnoreCase(src)) {
			return toType.isPrimitive() ? getPrimitiveDefaultValue() : null;
		}
		if (!toType.isPrimitive()
				&& ("null".equals(src) || "NULL".equals(src) || "Null"
						.equals(src))) {
			return null;
		}
		try {
			return valueOf(src);
		} catch (Exception e) {
			throw new FailToCastObjectException(String.format(
					"Fail to cast '%s' to <%s>", src, toType.getName()),
					Lang.unwrapThrow(e));
		}
	}
}
